package com.spzx.product.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.github.pagehelper.PageHelper;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.core.web.page.TableDataInfo;
import com.spzx.product.api.domain.ProductSkuVo;
import com.spzx.product.domain.Product;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.query.SkuQuery;
import com.spzx.product.service.*;
import com.spzx.product.vo.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Package: com.spzx.product.controller
 *
 * @Description:
 * @Author xiongkunYang
 * @Create 2025/5/28 9:18
 */
@Tag(name = "聚合数据")
@RestController
@RequestMapping("/channel")
@RequiredArgsConstructor
public class ChannelController extends BaseController {

    private final ICategoryService categoryService;
    private final IProductSkuService productSkuService;
    private final IBrandService brandService;
    private final IProductService productService;
    private final ISkuStockService skuStockService;
    private final IProductDetailsService productDetailsService;
    private final RedisTemplate<Object, Object> redisTemplate;
    private final ThreadPoolExecutor threadPoolExecutor;

    @Operation(summary = "获取首页数据")
    @GetMapping("/index")
    public AjaxResult index() {
        List<CategoryVo> levelOneCategory = this.categoryService.getLevelOneCategory();
        List<ProductSkuVo> topSale = this.productSkuService.getTopSale();
        IndexDataVo indexDataVo = IndexDataVo.builder().categoryList(levelOneCategory).productSkuList(topSale).build();
        return super.success(indexDataVo);
    }

    @Operation(summary = "获取分类嵌套列表")
    @GetMapping("/category")
    public AjaxResult category() {
        return success(categoryService.tree());
    }

    @Operation(summary = "显示商品列表")
    @Parameters({
            @Parameter(name = "pageNum", description = "当前页码"),
            @Parameter(name = "pageSize", description = "每页记录数")
    })
    @GetMapping("/skuList/{pageNum}/{pageSize}")
    public TableDataInfo skuList(@PathVariable Integer pageNum,
                                 @PathVariable Integer pageSize,
                                 SkuQuery skuQuery) {

        PageHelper.startPage(pageNum, pageSize);
        List<ProductSkuVo> list = productSkuService.productSkuList(skuQuery);
        return getDataTable(list);
    }

    @Operation(summary = "获取全部品牌")
    @GetMapping("/brand")
    public AjaxResult selectBrandAll() {
        return success(brandService.list());
    }

    @Operation(summary = "获取商品详情")
    @Parameters({
            @Parameter(name = "skuId", description = "商品skuId")
    })
    @GetMapping("/item/{skuId}")
    public AjaxResult item(@PathVariable Long skuId) {
        long start = Instant.now().toEpochMilli();

        //查询bitmap中是否有当前数据
        String key = "product:sku:data";
        Boolean flag = redisTemplate.opsForValue().getBit(key, skuId);
        if (Boolean.FALSE.equals(flag)) {
            throw new ServiceException("数据不存在");
        }

        ItemVo itemVo = new ItemVo();

        //获取sku信息
        CompletableFuture<Long> futureProductSku = CompletableFuture.supplyAsync(() -> {
            ProductSku productSku = productSkuService.getProductSku(skuId);
            itemVo.setProductSku(productSku);
            return productSku.getProductId();
        }, threadPoolExecutor);

        CompletableFuture<Void> futureProduct = futureProductSku.thenAcceptAsync(productId -> {
            //获取商品信息
            Product product = productService.getById(productId);
            //商品信息：轮播图列表
            String[] sliderUrlList = product.getSliderUrls().split(",");
            itemVo.setSliderUrlList(sliderUrlList);
            //商品信息:商品规格列表
            JSONArray specValueList = JSON.parseArray(product.getSpecValue());
            itemVo.setSpecValueList(specValueList);
        }, threadPoolExecutor);

        CompletableFuture<Void> futureDetails = futureProductSku.thenAcceptAsync(productId->{
            //商品详情图片
            itemVo.setDetailsImageUrlList(productDetailsService.getProductDetails(productId));
        });

        CompletableFuture<Void> futureSkuSpecValueMap = futureProductSku.thenAcceptAsync(productId->{
            //商品规格map数据
            itemVo.setSkuSpecValueMap(productSkuService.getSkuSpecValue(productId));
        });

        CompletableFuture<Void> futureSkuPrice = CompletableFuture.runAsync(()->{
            //商品价格
            itemVo.setSkuPrice(productSkuService.getSkuPrice(skuId));
        }, threadPoolExecutor);

        CompletableFuture<Void> futureSkuStock = CompletableFuture.runAsync(()->{
            //商品库存
            itemVo.setSkuStock(skuStockService.getSkuStock(skuId));
        }, threadPoolExecutor);

        CompletableFuture.allOf(
                futureSkuPrice,
                futureProduct,
                futureProductSku,
                futureDetails,
                futureSkuSpecValueMap,
                futureSkuStock
        ).join();

        System.out.println("用时:" + (Instant.now().toEpochMilli() - start) + "毫秒");
        return success(itemVo);
    }

}